package lws.com.liwushuo.view.fragment.bangdan;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import lws.com.liwushuo.R;
import lws.com.liwushuo.adapter.bangdan.Bangdan_danpin2_Adapter;
import lws.com.liwushuo.adapter.bangdan.Bangdan_danpin_FocusAdapter;
import lws.com.liwushuo.bean.bangdan.Bangdan_danpin2Bean;
import lws.com.liwushuo.bean.bangdan.Bangdan_danpinBean;
import lws.com.liwushuo.server.bangdan.Bangdan_danpin_Server;
import lws.com.liwushuo.server.bangdan.Bangdan_danpin_server2;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static lws.com.liwushuo.app.OurApp.context;

/**
 * A simple {@link Fragment} subclass.
 */
public class DanpinFragment extends Fragment implements ViewPager.OnPageChangeListener,Handler.Callback {
    private View view;
    private Bangdan_danpin_Server server;
    private int id;
    private LinearLayout headerView;
    private Handler handler = new Handler(this);
    private ViewPager viewPager;
    private ListView listView;
    private ImageView lunboPoint;
    private LinearLayout lunboPoints;
    private Bangdan_danpin_FocusAdapter lunboAdapter;
    private Bangdan_danpin_server2 server2;
    private Bangdan_danpin2_Adapter adapter2;
    private Map<Integer,List<Bangdan_danpin2Bean.DataBean.RecommendItemsBean>> map;
    private int currentPage;

    private TextView head_name,headname_short_description,head_favorites_count,head_price,head_description;
    private LinearLayout danpin_linearLayout;

    public DanpinFragment() {
        // Required empty public constructor
    }

    public DanpinFragment(int id) {
        this.id = id;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if(view != null){
            return view;
        }
        view = inflater.inflate(R.layout.fragment_danpin2, container, false);
        listView = (ListView) view.findViewById(R.id.bangdan_danpin_listView);
        danpin_linearLayout = ((LinearLayout) view.findViewById(R.id.bangdan_danpin_linearLayout));
        map = new ArrayMap<>();
        initView();
        setLast();
        return view;
    }
        private void setLast(){
            Retrofit.Builder builder = new Retrofit.Builder();
            Retrofit retrofit = builder.baseUrl("http://api.liwushuo.com").addConverterFactory(GsonConverterFactory.create()).build();
            server2 = retrofit.create(Bangdan_danpin_server2.class);
            server2.getBangdan_danpin2Bean(id,20,5).enqueue(new Callback<Bangdan_danpin2Bean>() {
                @Override
                public void onResponse(Call<Bangdan_danpin2Bean> call, Response<Bangdan_danpin2Bean> response) {
//
                    for(int i=0,j=0;i<response.body().getData().getRecommend_items().size()-2;i++,j++){
                        List<Bangdan_danpin2Bean.DataBean.RecommendItemsBean> list = new ArrayList<Bangdan_danpin2Bean.DataBean.RecommendItemsBean>();
                        list.add(response.body().getData().getRecommend_items().get(i));
                        list.add(response.body().getData().getRecommend_items().get(i+1));
                        i++;
                        map.put(j,list);
                    }
                        adapter2 = new Bangdan_danpin2_Adapter(map);
                    if(adapter2.getMap() == null){
                        adapter2.setMap(map);
                    }else {
                        map.putAll(map);
                    }
                    adapter2.notifyDataSetChanged();
                    listView.setAdapter(adapter2);
                }
                @Override
                public void onFailure(Call<Bangdan_danpin2Bean> call, Throwable t) {
                }
            });
        }
        private void initView(){
                if (headerView == null) {
                    //listView头部轮播View
                    headerView = ((LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.bangdan_danpin_item1, null));
                    //头部的viewpager
                    viewPager = ((ViewPager) headerView.findViewById(R.id.dabpin_lunboViewpager));
                    viewPager.addOnPageChangeListener(this);//轮播监听
//                    listView.setParallaxImageView(viewPager);
                    //头部小白点和小白点集合
                    lunboPoint = ((ImageView) headerView.findViewById(R.id.dabpin_lunboPoint));
                    lunboPoints = ((LinearLayout) headerView.findViewById(R.id.dabpin_lunboPoints));

                    head_name = ((TextView) headerView.findViewById(R.id.bangdan_danpin_name));
                    headname_short_description = ((TextView) headerView.findViewById(R.id.bangdan_danpin_short_description));
                    head_favorites_count = ((TextView) headerView.findViewById(R.id.bangdan_danpin_favorites_count));
                    head_price = ((TextView) headerView.findViewById(R.id.bangdan_danpin_price));
                    head_description = (TextView) headerView.findViewById(R.id.bangdan_danpin_description);
                }

                Retrofit.Builder builder = new Retrofit.Builder();
                Retrofit retrofit = builder.baseUrl("http://api.liwushuo.com").addConverterFactory(GsonConverterFactory.create()).build();
                server = retrofit.create(Bangdan_danpin_Server.class);

                server.getBangdan_danpinBean(id).enqueue(new Callback<Bangdan_danpinBean>() {
                    @Override
                    public void onResponse(Call<Bangdan_danpinBean> call, Response<Bangdan_danpinBean> response) {
                        Bangdan_danpinBean.DataBean dataBean = response.body().getData();
                        List<String> banners = dataBean.getImage_urls();
                        if (lunboAdapter == null) {
                            //设置轮播的适配器
                            lunboAdapter = new Bangdan_danpin_FocusAdapter(getContext(), banners,response.body().getData());
                            viewPager.setAdapter(lunboAdapter);
                            viewPager.setCurrentItem(1);//第一次的页面要设置为真正的第一张
                            //创建小白点
                            createPoint(banners);
                            //无限轮播
//            handler.obtainMessage(0, 1, 0).sendToTarget();
                            head_name.setText(dataBean.getName());
                            head_description.setText(dataBean.getDescription());
                            head_favorites_count.setText(dataBean.getFavorites_count()+"");
                            head_price.setText(dataBean.getPrice());
                            headname_short_description.setText(dataBean.getShort_description());
                            //listView添加头布局
                            listView.addHeaderView(headerView);
                        }
                    }
                    @Override
                    public void onFailure(Call<Bangdan_danpinBean> call, Throwable t) {

                    }
                });
        }



    private void createPoint(List<String> banners) {
        for (int i = 0; i < banners.size(); i++) {
            ImageView point = new ImageView(context);
            point.setImageResource(R.drawable.point);
            int p = (int) context.getResources().getDimension(R.dimen.point_padding);
            point.setPadding(p, p, p, p);
            lunboPoints.addView(point);
        }
        //第一次把圆点移动到第一位 不过这里为什么要post // TODO: 2016/10/13 为什么
        lunboPoint.post(new Runnable() {
            @Override
            public void run() {
                ViewCompat.setTranslationX(lunboPoint, lunboPoints.getLeft());
            }
        });
    }

    /**
     * viewpager滑动时，就小白点也要滑动
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        //value表示小白点要位移的距离，由当前的viewpager的位置+上viewpager的当前偏移量，
        // 乘上每个小白点的宽度，再加上装小白点的这个linearlayout的最左边位置
        float value = lunboPoints.getLeft() + (position - 1 + positionOffset) * lunboPoint.getWidth();
            /*
            *小白点位移的距离不能比装小白点的linearlayout最左边还小,因为我们前后加入两个图，
            * 所以当我们看到第一张图的时候，他的前面还有最后一张图，所以position的值有1变为0，
            * position - 1 + positionOffset 这个值算出来就是负数，然后value的值就会小于fPoints的最左边，
            * 然后移动就会移动超出了最左边，所以位移取比和getLeft的最大值，或getRight的最小值
            * 右边同理
            *
             */
        value = Math.max(value, lunboPoints.getLeft());//
        value = Math.min(value, lunboPoints.getRight() - lunboPoint.getWidth());//也不能大于最右边的距离
        ViewCompat.setTranslationX(lunboPoint, value);
    }

    /**
     * 页面选中的时候，需要注意头尾加了两个页面，
     * 这里要设置一下
     *
     * @param position
     */
    @Override
    public void onPageSelected(int position) {
        if (position == viewPager.getAdapter().getCount() - 1) {
            //滑到了最后一张，我们需要跳到第二张也就是真正的第一张图片
            viewPager.setCurrentItem(1, false);
        } else if (position == 0) {
            //滑到了第一张，我们需要跳到倒数第二张，也就是真正的最后一张图
            viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 2, false);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }


    /**
     * 无限轮播
     *
     * @param msg
     * @return
     */
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 0:
                if (viewPager != null) {
                    int arg1 = msg.arg1;//arg1是要跳转的页面
                    if (arg1 > viewPager.getAdapter().getCount() - 2) {
                        //这里也要判断跳转的是不是我们添加的假的数据
                        //这里跳转的是真正的最后一页，我们应该跳到第0页，也就是我们自己添加的页面
                        arg1 = 1;
                    }
                    viewPager.setCurrentItem(arg1, arg1 != 1);//如果要跳转到第一页，就必须设置跳转方式为false
                    Message message = handler.obtainMessage(0, ++arg1, 0);
                    currentPage = arg1;
                    handler.sendMessageDelayed(message, 5000);
                }
                break;
        }
        return true;
    }

    @Override
    public void onStop() {
        super.onStop();
        handler.removeMessages(0);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (viewPager != null && viewPager.getAdapter() != null) {
            handler.obtainMessage(0, currentPage, 0).sendToTarget();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeMessages(0);
    }

}
